package com.dpwgc.demo.service;

import com.dpwgc.demo.config.SftpConfig;
import com.dpwgc.demo.utils.DateUtil;
import com.dpwgc.demo.utils.ResultUtil;
import com.dpwgc.demo.utils.SftpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

@Service
public class UploadService {

    @Autowired
    DateUtil dateUtil;

    @Value("${sftp.hostname}")
    String hostname;
    @Value("${sftp.port}")
    String port;
    @Value("${sftp.username}")
    String username;
    @Value("${sftp.password}")
    String password;
    @Value("${sftp.timeout}")
    String timeout;


    /**
     * 上传文件
     * @param url 上传路径
     * @param multipartFile 文件
     * @param fileRename 文件命名
     * @return
     */
    public ResultUtil<Object> uploadFileService(String url, MultipartFile multipartFile,String fileRename) throws Exception {

        ResultUtil<Object> resultUtil = new ResultUtil<>();

        SftpUtil sftpUtil = new SftpUtil(3, 6000);

        SftpConfig sftpConfig = new SftpConfig(hostname, Integer.parseInt(port), username, password, Integer.parseInt(timeout), url);
        // 获取文件名
        String fileName = multipartFile.getOriginalFilename();
        // 获取文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));

        //MultipartFile转File
        File file = multipartFileToFile(multipartFile,fileRename,suffix);

        //上传
        sftpUtil.upload(url,file,sftpConfig);

        //该方法会生成临时文件（可用该方式删除）
        File del = new File(file.toURI());
        del.delete();

        resultUtil.setCode(200);
        resultUtil.setMsg("操作成功");
        resultUtil.setData(url+"/"+fileRename+suffix);
        return resultUtil;
    }

    /**
     * MultipartFile转File
     * @param multipartFile
     * @return
     * @throws Exception
     */
    public static File multipartFileToFile(MultipartFile multipartFile,String fileRename,String suffix) throws Exception {
        File toFile = null;
        if (multipartFile.equals("") || multipartFile.getSize() <= 0) {
            multipartFile = null;
        } else {
            InputStream ins = null;
            ins = multipartFile.getInputStream();
            toFile = new File(fileRename+suffix);
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }
    public static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
